package com.zhitan.ems.app.stat.facade.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhitan.ems.app.iot.entity.DeviceEntity;
import com.zhitan.ems.app.iot.entity.DeviceGroupEntity;
import com.zhitan.ems.app.iot.entity.GroupEntity;
import com.zhitan.ems.app.iot.enums.ENERGY_TYPES_ENUM;
import com.zhitan.ems.app.iot.service.DeviceGroupService;
import com.zhitan.ems.app.iot.service.DeviceService;
import com.zhitan.ems.app.iot.service.GroupService;
import com.zhitan.ems.app.iot.vo.DeviceGroupVO;
import com.zhitan.ems.app.stat.entity.StatisticsDayEntity;
import com.zhitan.ems.app.stat.entity.StatisticsHourlyEntity;
import com.zhitan.ems.app.stat.entity.StatisticsMonthEntity;
import com.zhitan.ems.app.stat.entity.StatisticsYearEntity;
import com.zhitan.ems.app.stat.facade.StatFacade;
import com.zhitan.ems.app.stat.service.StatisticsDayService;
import com.zhitan.ems.app.stat.service.StatisticsHourlyService;
import com.zhitan.ems.app.stat.service.StatisticsMonthService;
import com.zhitan.ems.app.stat.service.StatisticsYearService;
import com.zhitan.ems.app.stat.vo.FlowDataVo;
import com.zhitan.ems.common.extra.utils.DateUtil;
import com.zhitan.ems.common.extra.utils.JsonUtil;
import com.zhitan.ems.common.utils.DateUtils;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Component
public class StatFacadeImpl implements StatFacade {
	@Autowired
	private StatisticsDayService statisticsDayService;
	@Autowired
	private StatisticsHourlyService statisticsHourlyService;
	@Autowired
	private StatisticsMonthService statisticsMonthService;
	@Autowired
	private StatisticsYearService statisticsYearService;
	 @Autowired
	    private DeviceService deviceService;
	 @Autowired
	    private DeviceGroupService deviceGroupService;
	    @Autowired
		private GroupService groupService;
	/**
	 * 获取小时统计数据（昨天的合计数据），包括同比和环比
	 */
	@Override
	public Map<String, Object> getHomeHourlyStatistics(String statTime,Integer energyType) {
		Map<String, Object> result = new HashMap<>();
		 String tips="天统计";
        Date curDate = new Date();
		Date startOfDay = DateUtils.getStartOfDate(curDate);
		Date endOfDay = DateUtils.getEndOfDate(curDate);
		// 获取前天的日期（用于环比）
		Date beforeDay = DateUtils.addDays(curDate, -1);
		Date startOfBeforeDay = DateUtils.getStartOfDate(beforeDay);
		Date endOfBeforeDay = DateUtils.getEndOfDate(beforeDay);
		// 获取去年同一天的日期（用于同比）
		Date lastYearDay = DateUtils.addYears(curDate, -1);
		Date startOfLastYearDay = DateUtils.getStartOfDate(lastYearDay);
		Date endOfLastYearDay = DateUtils.getEndOfDate(lastYearDay);
		 Integer statTimeType=2;
		if (statTime == null) {
		} else if (statTime.length() == 10) {
		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
		     statTimeType=2;
		     startOfDay = DateUtils.getStartOfDate(curDate);
 		     endOfDay = DateUtils.getEndOfDate(curDate);
		} else if (statTime.length() == 7) {
			 curDate = DateUtil.parse(statTime, "yyyy-MM");
			 startOfDay = DateUtil.getStartOfMonth(curDate);
			 endOfDay = DateUtil.getEndOfMonth(curDate);
			 // 获取前天的日期（用于环比）
			 beforeDay = DateUtils.addMonths(curDate, -1);
			 startOfBeforeDay = DateUtil.getStartOfMonth(beforeDay);
			 endOfBeforeDay = DateUtil.getEndOfMonth(beforeDay);
			 // 获取去年同一天的日期（用于同比）
			 lastYearDay = DateUtils.addYears(curDate, -1);
			 startOfLastYearDay = DateUtil.getStartOfMonth(lastYearDay);
			 endOfLastYearDay = DateUtil.getEndOfMonth(lastYearDay);
			 statTimeType=3;
			 tips="月统计";
		} else if (statTime.length() == 4) {
		     curDate = DateUtil.parse(statTime, "yyyy");
			 startOfDay = DateUtil.getStartOfYear(curDate);
			 endOfDay = DateUtil.getEndOfYear(curDate);
			 // 获取前天的日期（用于环比）
			 beforeDay = DateUtils.addYears(curDate, -1);
			 startOfBeforeDay = DateUtil.getStartOfYear(beforeDay);
			 endOfBeforeDay = DateUtil.getEndOfYear(beforeDay);
			 // 获取去年同一天的日期（用于同比）
			 lastYearDay = DateUtils.addYears(curDate, -2);
			 startOfLastYearDay = DateUtil.getStartOfYear(lastYearDay);
			 endOfLastYearDay = DateUtil.getEndOfYear(lastYearDay);
			 statTimeType=4;
			 tips="年统计";
		}
	
	 	QueryWrapper<GroupEntity> queryGroupWrapper=new QueryWrapper<>();
    	queryGroupWrapper.orderByDesc("group_id");
    	queryGroupWrapper.eq("parent_group_id", 0);
        List<GroupEntity> groupList = groupService.list(queryGroupWrapper);
        List<Long>  firstGroupIds=groupList.stream().map(GroupEntity::getGroupId).collect(Collectors.toList());
        if(firstGroupIds==null||firstGroupIds.size()<=0) {
 			return result;
 		}
 		List<DeviceGroupEntity> totalDeviceList= deviceGroupService.listByGroupId(firstGroupIds, energyType,1);//分组有效设备查询
 		List<Long> deviceIdList = totalDeviceList.stream().map(DeviceGroupEntity::getDeviceId).collect(Collectors.toList());
 		log.info("=======deviceIdList========"+JsonUtil.getJsonByObj(deviceIdList));
		// 查询昨天的小时统计数据
		QueryWrapper<StatisticsHourlyEntity> dayQuery = new QueryWrapper<>();
		dayQuery.select(
				"energy_type as energyType", 
				"COUNT(id) as count", 
				"SUM(sum_value) as sumValue", 
				"AVG(average_value) as totalAvg", 
				"MIN(min_value) as totalMin", 
				"MAX(max_value) as totalMax", 
				"SUM(count) as totalCount"
			);
		dayQuery.between("hour", startOfDay, endOfDay);
		dayQuery.eq("cost_state",10);
		dayQuery.eq(energyType!=null,"energy_type",energyType);
		dayQuery.in("device_id",deviceIdList);
		dayQuery.eq("statistics_type",10);
		dayQuery.groupBy("energy_type"); 
		 List<Map<String, Object>> dayData = statisticsHourlyService.listMaps(dayQuery);
		// 查询前天的小时统计数据（用于环比）
		QueryWrapper<StatisticsHourlyEntity> beforeYesterdayQuery = new QueryWrapper<>();
		beforeYesterdayQuery.select(
				"energy_type as energyType", 
				"COUNT(id) as count", 
				"SUM(sum_value) as sumValue", 
				"AVG(average_value) as totalAvg", 
				"MIN(min_value) as totalMin", 
				"MAX(max_value) as totalMax", 
				"SUM(count) as totalCount"
			);
		beforeYesterdayQuery.between("hour", startOfBeforeDay, endOfBeforeDay);
		beforeYesterdayQuery.eq("cost_state",10);
		beforeYesterdayQuery.in("device_id",deviceIdList);
		beforeYesterdayQuery.eq(energyType!=null,"energy_type",energyType);
		beforeYesterdayQuery.groupBy("energy_type"); 
		 List<Map<String, Object>> beforedayData = statisticsHourlyService.listMaps(beforeYesterdayQuery);
		// 查询上周同一天的小时统计数据（用于同比）
		QueryWrapper<StatisticsHourlyEntity> lastYearDayQuery = new QueryWrapper<>();
		lastYearDayQuery.select(
			"energy_type as energyType", 
			"COUNT(id) as count", 
			"SUM(sum_value) as sumValue", 
			"AVG(average_value) as totalAvg", 
			"MIN(min_value) as totalMin", 
			"MAX(max_value) as totalMax", 
			"SUM(count) as totalCount"
		);
		lastYearDayQuery.between("hour", startOfLastYearDay, endOfLastYearDay);
		lastYearDayQuery.eq("cost_state",10);
		lastYearDayQuery.eq(energyType!=null,"energy_type",energyType);
		lastYearDayQuery.eq("statistics_type",10);
		lastYearDayQuery.in("device_id",deviceIdList);
		lastYearDayQuery.groupBy("energy_type"); 
		List<Map<String, Object>> lastYearDayData = statisticsHourlyService.listMaps(lastYearDayQuery);
		
		for (Map<String, Object> stat : dayData) {
        	Integer energyTypeKey = (Integer) stat.get("energyType");
        	ENERGY_TYPES_ENUM energyTypeEnum=ENERGY_TYPES_ENUM.findByCode(energyTypeKey);
            stat.put("statisticsTypeName", energyTypeEnum.getName());
            stat.put("statisticsTypeDw", energyTypeEnum.getDw());
        }
		for (Map<String, Object> stat : beforedayData) {
        	Integer energyTypeKey = (Integer) stat.get("energyType");
        	ENERGY_TYPES_ENUM energyTypeEnum=ENERGY_TYPES_ENUM.findByCode(energyTypeKey);
            stat.put("statisticsTypeName", energyTypeEnum.getName());
            stat.put("statisticsTypeDw", energyTypeEnum.getDw());
        }
		for (Map<String, Object> stat : lastYearDayData) {
        	Integer energyTypeKey = (Integer) stat.get("energyType");
        	ENERGY_TYPES_ENUM energyTypeEnum=ENERGY_TYPES_ENUM.findByCode(energyTypeKey);
            stat.put("statisticsTypeName", energyTypeEnum.getName());
            stat.put("statisticsTypeDw", energyTypeEnum.getDw());
        }
		result.put("dayData", dayData);
		result.put("beforedayData", beforedayData);
		result.put("lastYearDayData", lastYearDayData);
		result.put("statTime",statTime);
		result.put("type", tips);
		
		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
		String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
		if(statTimeType==2) {//天
		}else if(statTimeType==3) {//月
			 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
			 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
		}else if(statTimeType==4) {//月
			 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
			 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
		}
		// 查询昨天的小时统计数据
		QueryWrapper<StatisticsHourlyEntity> dayListQuery = new QueryWrapper<>();
		dayListQuery.select(
				hourSql,
				"energy_type as energyType", 
				"COUNT(id) as count", 
				"SUM(sum_value) as sumValue", 
				"AVG(average_value) as totalAvg", 
				"MIN(min_value) as totalMin", 
				"MAX(max_value) as totalMax", 
				"SUM(count) as totalCount"
			);
		dayListQuery.between("hour", startOfDay, endOfDay);
		dayListQuery.eq("cost_state",10);
		dayListQuery.eq("statistics_type",10);
		dayListQuery.in("device_id",deviceIdList);
		dayListQuery.eq(energyType!=null,"energy_type",energyType);
		dayListQuery.groupBy(hourGroupSql,"energy_type"); 
		
		List<Map<String, Object>> dayListData = statisticsHourlyService.listMaps(dayListQuery);
		for (Map<String, Object> stat : dayListData) {
        	Integer energyTypeKey = (Integer) stat.get("energyType");
        	ENERGY_TYPES_ENUM energyTypeEnum=ENERGY_TYPES_ENUM.findByCode(energyTypeKey);
            stat.put("statisticsTypeName", energyTypeEnum.getName());
            stat.put("statisticsTypeDw", energyTypeEnum.getDw());
        }
		result.put("dayListData", dayListData);
		return result;
	}
	@Override
	public Map<String, Object> getHourlyStatisticsRanking(String statTime,Integer energyType,Integer top) {
		Map<String, Object> result = new HashMap<>();
		String tips="天统计";
		Date curDate = new Date();
		Date startOfDay = DateUtils.getStartOfDate(curDate);
		Date endOfDay = DateUtils.getEndOfDate(curDate);
		if (statTime == null) {
		} else if (statTime.length() == 10) {
			curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
			 startOfDay = DateUtils.getStartOfDate(curDate);
 		     endOfDay = DateUtils.getEndOfDate(curDate);
		} else if (statTime.length() == 7) {
			curDate = DateUtil.parse(statTime, "yyyy-MM");
			startOfDay = DateUtil.getStartOfMonth(curDate);
			endOfDay = DateUtil.getEndOfMonth(curDate);
			tips="月统计";
		} else if (statTime.length() == 4) {
			curDate = DateUtil.parse(statTime, "yyyy");
			startOfDay = DateUtil.getStartOfYear(curDate);
			endOfDay = DateUtil.getEndOfYear(curDate);
			tips="年统计";
		}
		result.put("statTime",statTime);
		result.put("type", tips);
		// 查询昨天的小时统计数据
		QueryWrapper<StatisticsHourlyEntity> dayListQuery = new QueryWrapper<>();
		dayListQuery.select(
				"device_code as deviceCode", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as sumValue", 
				"AVG(average_value) as totalAvg", 
				"MIN(min_value) as totalMin", 
				"MAX(max_value) as totalMax", 
				"SUM(count) as totalCount"
				);
//		"SUM(carbon_emissions) as carbonEmissions", 
//		"SUM(cost_money) as cost_money", 
		dayListQuery.between("hour", startOfDay, endOfDay);
		dayListQuery.eq("cost_state",10);
		dayListQuery.eq("statistics_type",10);
		dayListQuery.eq(energyType!=null,"energy_type",energyType);
		dayListQuery.groupBy("device_code"); 
		dayListQuery.orderByDesc("sumValue");
		dayListQuery.last(" limit "+top);
		List<Map<String, Object>> dayListData = statisticsHourlyService.listMaps(dayListQuery);
		for (Map<String, Object> stat : dayListData) {
			String deviceCode = (String) stat.get("deviceCode");
			DeviceEntity device= deviceService.getDeviceByDeviceCode(deviceCode);
			if(device!=null) {
				stat.put("deviceName", device.getDeviceName());
				ENERGY_TYPES_ENUM energyTypeEnum=ENERGY_TYPES_ENUM.findByCode(device.getEnergyType());
				stat.put("statisticsTypeName", energyTypeEnum.getName());
				stat.put("statisticsTypeDw", energyTypeEnum.getDw());
			}
		}
		result.put("dayListData", dayListData);
		return result;
	}
	/**
	 * 获取天统计数据，包括同比和环比
	 */
	@Override
	public  Map<String, Object> getDailyStatistics(String deviceCode,String address,Long groupId) {
		Map<String, Object> result = new HashMap<>();

		// 获取昨天的日期
		Date yesterday = DateUtils.addDays(new Date(), -1);
		Date startOfYesterday = DateUtils.getStartOfDate(yesterday);
		Date endOfYesterday = DateUtils.getEndOfDate(yesterday);

		// 查询昨天的天统计数据
		QueryWrapper<StatisticsDayEntity> yesterdayQuery = new QueryWrapper<>();
		yesterdayQuery.between("day", startOfYesterday, endOfYesterday);
		yesterdayQuery.eq(deviceCode!=null,"device_code", deviceCode);
		yesterdayQuery.eq(address!=null,"address", address);
		yesterdayQuery.eq(groupId!=null,"group_id", groupId);
		// 计算昨天的合计数据
		yesterdayQuery.select("SUM(sum_value) as totalSum", "SUM(average_value) as totalAvg",
				"SUM(min_value) as totalMin", "SUM(max_value) as totalMax", "SUM(count) as totalCount");

		Map<String, Object> yesterdayData = statisticsDayService.getMap(yesterdayQuery);

		// 获取前天的日期（用于环比）
		Date beforeYesterday = DateUtils.addDays(new Date(), -2);
		Date startOfBeforeYesterday = DateUtils.getStartOfDate(beforeYesterday);
		Date endOfBeforeYesterday = DateUtils.getEndOfDate(beforeYesterday);

		// 查询前天的天统计数据（用于环比）
		QueryWrapper<StatisticsDayEntity> beforeYesterdayQuery = new QueryWrapper<>();
		beforeYesterdayQuery.between("day", startOfBeforeYesterday, endOfBeforeYesterday);
		beforeYesterdayQuery.select("SUM(sum_value) as totalSum");
		beforeYesterdayQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeYesterdayQuery.eq(address!=null,"address", address);
		beforeYesterdayQuery.eq(groupId!=null,"group_id", groupId);
		Map<String, Object> beforeYesterdayData = statisticsDayService.getMap(beforeYesterdayQuery);

		// 获取上周同一天的日期（用于同比）
		Date lastWeek = DateUtils.addDays(new Date(), -8);
		Date startOfLastWeek = DateUtils.getStartOfDate(lastWeek);
		Date endOfLastWeek = DateUtils.getEndOfDate(lastWeek);

		// 查询上周同一天的天统计数据（用于同比）
		QueryWrapper<StatisticsDayEntity> lastWeekQuery = new QueryWrapper<>();
		lastWeekQuery.between("day", startOfLastWeek, endOfLastWeek);
		lastWeekQuery.select("SUM(sum_value) as totalSum");
		lastWeekQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastWeekQuery.eq(address!=null,"address", address);
		lastWeekQuery.eq(groupId!=null,"group_id", groupId);
		Map<String, Object> lastWeekData = statisticsDayService.getMap(lastWeekQuery);

		// 计算环比增长率
		Double yesterdaySum = (Double) (yesterdayData != null && yesterdayData.get("totalSum") != null
				? yesterdayData.get("totalSum")
				: 0.0);
		Double beforeYesterdaySum = (Double) (beforeYesterdayData != null && beforeYesterdayData.get("totalSum") != null
				? beforeYesterdayData.get("totalSum")
				: 0.0);
		double chainGrowthRate = 0.0;
		if (beforeYesterdaySum != 0.0) {
			chainGrowthRate = ((yesterdaySum - beforeYesterdaySum) / beforeYesterdaySum) * 100;
		}

		// 计算同比增长率
		Double lastWeekSum = (Double) (lastWeekData != null && lastWeekData.get("totalSum") != null
				? lastWeekData.get("totalSum")
				: 0.0);
		double yearGrowthRate = 0.0;
		if (lastWeekSum != 0.0) {
			yearGrowthRate = ((yesterdaySum - lastWeekSum) / lastWeekSum) * 100;
		}

		// 构建返回结果
		result.put("yesterdayData", yesterdayData);
		result.put("beforeYesterdayData", beforeYesterdayData);
		result.put("lastWeekData", lastWeekData);
		
		result.put("chainGrowthRate", String.format("%.2f%%", chainGrowthRate));
		result.put("yearGrowthRate", String.format("%.2f%%", yearGrowthRate));
		result.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", yesterday));
		result.put("type", "天统计");

		return result;
	}

	/**
	 * 获取月统计数据，包括同比和环比
	 */
	@Override
	public  Map<String, Object> getMonthlyStatistics(String deviceCode,String address,Long groupId) {
		Map<String, Object> result = new HashMap<>();

		// 获取上个月的日期
		Date lastMonth = DateUtils.addMonths(new Date(), -1);
		Date startOfLastMonth = DateUtils.getMonthFirstDayOfDate(lastMonth);
		Date endOfLastMonth = DateUtils.getMonthLastDayOfDate(lastMonth);

		// 查询上个月的月统计数据
		QueryWrapper<StatisticsMonthEntity> lastMonthQuery = new QueryWrapper<>();
		lastMonthQuery.between("month", startOfLastMonth, endOfLastMonth);
		lastMonthQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastMonthQuery.eq(address!=null,"address", address);
		lastMonthQuery.eq(groupId!=null,"group_id", groupId);
		// 计算上个月的合计数据
		lastMonthQuery.select("SUM(sum_value) as totalSum", "SUM(average_value) as totalAvg",
				"SUM(min_value) as totalMin", "SUM(max_value) as totalMax", "SUM(count) as totalCount");

		Map<String, Object> lastMonthData = statisticsMonthService.getMap(lastMonthQuery);

		// 获取上上个月的日期（用于环比）
		Date beforeLastMonth = DateUtils.addMonths(new Date(), -2);
		Date startOfBeforeLastMonth = DateUtils.getMonthFirstDayOfDate(beforeLastMonth);
		Date endOfBeforeLastMonth = DateUtils.getMonthLastDayOfDate(beforeLastMonth);

		// 查询上上个月的月统计数据（用于环比）
		QueryWrapper<StatisticsMonthEntity> beforeLastMonthQuery = new QueryWrapper<>();
		beforeLastMonthQuery.between("month", startOfBeforeLastMonth, endOfBeforeLastMonth);
		beforeLastMonthQuery.select("SUM(sum_value) as totalSum");
		beforeLastMonthQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeLastMonthQuery.eq(address!=null,"address", address);
		beforeLastMonthQuery.eq(groupId!=null,"group_id", groupId);
		Map<String, Object> beforeLastMonthData = statisticsMonthService.getMap(beforeLastMonthQuery);

		// 获取去年同期的日期（用于同比）
		Date lastYearSameMonth = DateUtils.addYears(new Date(), -1);
		lastYearSameMonth = DateUtils.addMonths(lastYearSameMonth, -1); // 上个月
		Date startOfLastYearSameMonth = DateUtils.getMonthFirstDayOfDate(lastYearSameMonth);
		Date endOfLastYearSameMonth = DateUtils.getMonthLastDayOfDate(lastYearSameMonth);

		// 查询去年同期的月统计数据（用于同比）
		QueryWrapper<StatisticsMonthEntity> lastYearQuery = new QueryWrapper<>();
		lastYearQuery.between("month", startOfLastYearSameMonth, endOfLastYearSameMonth);
		lastYearQuery.select("SUM(sum_value) as totalSum");
		lastYearQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastYearQuery.eq(address!=null,"address", address);
		beforeLastMonthQuery.eq(groupId!=null,"group_id", groupId);
		Map<String, Object> lastYearData = statisticsMonthService.getMap(lastYearQuery);

		// 计算环比增长率
		Double lastMonthSum = (Double) (lastMonthData != null && lastMonthData.get("totalSum") != null
				? lastMonthData.get("totalSum")
				: 0.0);
		Double beforeLastMonthSum = (Double) (beforeLastMonthData != null && beforeLastMonthData.get("totalSum") != null
				? beforeLastMonthData.get("totalSum")
				: 0.0);
		double chainGrowthRate = 0.0;
		if (beforeLastMonthSum != 0.0) {
			chainGrowthRate = ((lastMonthSum - beforeLastMonthSum) / beforeLastMonthSum) * 100;
		}

		// 计算同比增长率
		Double lastYearSum = (Double) (lastYearData != null && lastYearData.get("totalSum") != null
				? lastYearData.get("totalSum")
				: 0.0);
		double yearGrowthRate = 0.0;
		if (lastYearSum != 0.0) {
			yearGrowthRate = ((lastMonthSum - lastYearSum) / lastYearSum) * 100;
		}

		// 构建返回结果
		result.put("lastMonthData", lastMonthData);
		result.put("beforeLastMonthData", beforeLastMonthData);
		result.put("lastYearData", lastYearData);
		result.put("chainGrowthRate", String.format("%.2f%%", chainGrowthRate));
		result.put("yearGrowthRate", String.format("%.2f%%", yearGrowthRate));
		result.put("date", DateUtils.parseDateToStr("yyyy-MM", lastMonth));
		result.put("type", "月统计");

		return result;
	}

	/**
	 * 获取年统计数据，包括同比和环比
	 */
	@Override
	public  Map<String, Object> getYearlyStatistics(String deviceCode,String address, Long groupId) {
		Map<String, Object> result = new HashMap<>();

		// 获取去年的年份
		Date lastYear = DateUtils.addYears(new Date(), -1);
		Date startOfLastYear = DateUtils.getYearFirstDayOfDate(lastYear);
		Date endOfLastYear = DateUtils.getYearLastDayOfDate(lastYear);

		// 查询去年的年统计数据
		QueryWrapper<StatisticsYearEntity> lastYearQuery = new QueryWrapper<>();
		lastYearQuery.between("year", getYearValue(startOfLastYear), getYearValue(endOfLastYear));
		lastYearQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastYearQuery.eq(address!=null,"address", address);
		lastYearQuery.eq(groupId!=null,"group_id", groupId);
		// 计算去年的合计数据
		lastYearQuery.select("SUM(sum_value) as totalSum", "SUM(average_value) as totalAvg",
				"SUM(min_value) as totalMin", "SUM(max_value) as totalMax", "SUM(count) as totalCount");

		Map<String, Object> lastYearData = statisticsYearService.getMap(lastYearQuery);

		// 获取前年的日期（用于环比）
		Date beforeLastYear = DateUtils.addYears(new Date(), -2);
		Date startOfBeforeLastYear = DateUtils.getYearFirstDayOfDate(beforeLastYear);
		Date endOfBeforeLastYear = DateUtils.getYearLastDayOfDate(beforeLastYear);

		// 查询前年的年统计数据（用于环比）
		QueryWrapper<StatisticsYearEntity> beforeLastYearQuery = new QueryWrapper<>();
		beforeLastYearQuery.between("year", getYearValue(startOfBeforeLastYear), getYearValue(endOfBeforeLastYear));
		beforeLastYearQuery.select("SUM(sum_value) as totalSum");
		beforeLastYearQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeLastYearQuery.eq(address!=null,"address", address);
		beforeLastYearQuery.eq(groupId!=null,"group_id", groupId);
		Map<String, Object> beforeLastYearData = statisticsYearService.getMap(beforeLastYearQuery);

		// 获取前年的前一年日期（用于同比）
		Date threeYearsAgo = DateUtils.addYears(new Date(), -3);
		Date startOfThreeYearsAgo = DateUtils.getYearFirstDayOfDate(threeYearsAgo);
		Date endOfThreeYearsAgo = DateUtils.getYearLastDayOfDate(threeYearsAgo);

		// 查询前年的前一年年统计数据（用于同比）
		QueryWrapper<StatisticsYearEntity> threeYearsAgoQuery = new QueryWrapper<>();
		threeYearsAgoQuery.between("year", getYearValue(startOfThreeYearsAgo), getYearValue(endOfThreeYearsAgo));
		threeYearsAgoQuery.select("SUM(sum_value) as totalSum");
		threeYearsAgoQuery.eq(deviceCode!=null,"device_code", deviceCode);
		threeYearsAgoQuery.eq(address!=null,"address", address);
		threeYearsAgoQuery.eq(groupId!=null,"group_id", groupId);
		Map<String, Object> threeYearsAgoData = statisticsYearService.getMap(threeYearsAgoQuery);

		// 计算环比增长率
		Double lastYearSum = (Double) (lastYearData != null && lastYearData.get("totalSum") != null
				? lastYearData.get("totalSum")
				: 0.0);
		Double beforeLastYearSum = (Double) (beforeLastYearData != null && beforeLastYearData.get("totalSum") != null
				? beforeLastYearData.get("totalSum")
				: 0.0);
		double chainGrowthRate = 0.0;
		if (beforeLastYearSum != 0.0) {
			chainGrowthRate = ((lastYearSum - beforeLastYearSum) / beforeLastYearSum) * 100;
		}

		// 计算同比增长率
		Double threeYearsAgoSum = (Double) (threeYearsAgoData != null && threeYearsAgoData.get("totalSum") != null
				? threeYearsAgoData.get("totalSum")
				: 0.0);
		double yearGrowthRate = 0.0;
		if (threeYearsAgoSum != 0.0) {
			yearGrowthRate = ((lastYearSum - threeYearsAgoSum) / threeYearsAgoSum) * 100;
		}

		// 构建返回结果
		result.put("lastMonthData", lastYearData);
		result.put("beforeLastYearData", beforeLastYearData);
		result.put("threeYearsAgoData", threeYearsAgoData);
		result.put("chainGrowthRate", String.format("%.2f%%", chainGrowthRate));
		result.put("yearGrowthRate", String.format("%.2f%%", yearGrowthRate));
		result.put("date", String.valueOf(getYearValue(startOfLastYear)));
		result.put("type", "年统计");

		return result;
	}

	/**
	 * 从日期中提取年份值
	 */
	private int getYearValue(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.YEAR);
	}

	@Override
	public Map<String, Object> list24HourlyStatistics(String dateStr,String deviceCode, String address, Long groupId,Integer groupType) {
		Map<String, Object> result = new HashMap<>();
		// 获取昨天的日期
		Date yesterday = DateUtil.parse(dateStr, "yyyy-MM-dd");
		Date startOfYesterday = DateUtils.getStartOfDate(yesterday);
		Date endOfYesterday = DateUtils.getEndOfDate(yesterday);

		// 查询昨天的小时统计数据
		QueryWrapper<StatisticsHourlyEntity> yesterdayQuery = new QueryWrapper<>();
		yesterdayQuery.between("hour", startOfYesterday, endOfYesterday);
		yesterdayQuery.eq(deviceCode!=null,"device_code", deviceCode);
		yesterdayQuery.eq(address!=null,"address", address);
		yesterdayQuery.eq(groupId!=null,"group_id", groupId);
		yesterdayQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsHourlyEntity> yesterdayData = statisticsHourlyService.list(yesterdayQuery);

		// 获取前天的日期（用于环比）
		Date beforeYesterday = DateUtils.addDays(yesterday, -1);
		Date startOfBeforeYesterday = DateUtils.getStartOfDate(beforeYesterday);
		Date endOfBeforeYesterday = DateUtils.getEndOfDate(beforeYesterday);

		// 查询前天的小时统计数据（用于环比）
		QueryWrapper<StatisticsHourlyEntity> beforeYesterdayQuery = new QueryWrapper<>();
		beforeYesterdayQuery.between("hour", startOfBeforeYesterday, endOfBeforeYesterday);
		beforeYesterdayQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeYesterdayQuery.eq(address!=null,"address", address);
		beforeYesterdayQuery.eq(groupId!=null,"group_id", groupId);
		beforeYesterdayQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsHourlyEntity> beforeYesterdayData = statisticsHourlyService.list(beforeYesterdayQuery);

		// 获取上周同一天的日期（用于同比）
		Date lastWeek = DateUtils.addDays(yesterday, -7);
		Date startOfLastWeek = DateUtils.getStartOfDate(lastWeek);
		Date endOfLastWeek = DateUtils.getEndOfDate(lastWeek);
		// 查询上周同一天的小时统计数据（用于同比）
		QueryWrapper<StatisticsHourlyEntity> lastWeekQuery = new QueryWrapper<>();
		lastWeekQuery.between("hour", startOfLastWeek, endOfLastWeek);
		lastWeekQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastWeekQuery.eq(address!=null,"address", address);
		lastWeekQuery.eq(groupId!=null,"group_id", groupId);
		lastWeekQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsHourlyEntity> lastWeekData = statisticsHourlyService.list(lastWeekQuery);
		// 构建返回结果
		result.put("yesterdayData", yesterdayData);
		result.put("beforeYesterdayData", beforeYesterdayData);
		result.put("lastWeekData", lastWeekData);
		result.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", yesterday));
		result.put("type", "小时统计");
		return result;
	}

	@Override
	public Map<String, Object> list30DailyStatistics(String monthStr,String deviceCode, String address, Long groupId,Integer groupType) {
		Map<String, Object> result = new HashMap<>();
		// 获取昨天的日期
		Date curMonth = DateUtil.parse(monthStr, "yyyy-MM");
		Date startOfYesterday = DateUtils.getStartOfDate(DateUtil.getStartOfMonth(curMonth));
		Date endOfYesterday = DateUtils.getEndOfDate(DateUtil.getEndOfMonth(curMonth));

		// 查询昨天的天统计数据
		QueryWrapper<StatisticsDayEntity> yesterdayQuery = new QueryWrapper<>();
		yesterdayQuery.between("day", startOfYesterday, endOfYesterday);
		yesterdayQuery.eq(deviceCode!=null,"device_code", deviceCode);
		yesterdayQuery.eq(address!=null,"address", address);
		yesterdayQuery.eq(groupId!=null,"group_id", groupId);
		yesterdayQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsDayEntity> yesterdayData = statisticsDayService.list(yesterdayQuery);

		// 获取前天的日期（用于环比）
		Date preMonth =DateUtils.addMonths(curMonth, -1);
		Date startOfBeforeYesterday = DateUtils.getStartOfDate(DateUtil.getStartOfMonth(preMonth));
		Date endOfBeforeYesterday = DateUtils.getEndOfDate(DateUtil.getEndOfMonth(preMonth));

		// 查询前天的天统计数据（用于环比）
		QueryWrapper<StatisticsDayEntity> beforeYesterdayQuery = new QueryWrapper<>();
		beforeYesterdayQuery.between("day", startOfBeforeYesterday, endOfBeforeYesterday);
		beforeYesterdayQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeYesterdayQuery.eq(address!=null,"address", address);
		beforeYesterdayQuery.eq(groupId!=null,"group_id", groupId);
		beforeYesterdayQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsDayEntity> beforeYesterdayData = statisticsDayService.list(beforeYesterdayQuery);

		// 获取去年同一天的日期（用于同比）
		Date preYearMonth = DateUtils.addYears(curMonth, -1);
		Date startOfLastWeek = DateUtils.getStartOfDate(DateUtil.getStartOfMonth(preYearMonth));
		Date endOfLastWeek = DateUtils.getEndOfDate(DateUtil.getEndOfMonth(preYearMonth));

		// 查询上周同一天的天统计数据（用于同比）
		QueryWrapper<StatisticsDayEntity> lastWeekQuery = new QueryWrapper<>();
		lastWeekQuery.between("day", startOfLastWeek, endOfLastWeek);
		lastWeekQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastWeekQuery.eq(address!=null,"address", address);
		lastWeekQuery.eq(groupId!=null,"group_id", groupId);
		lastWeekQuery.eq(groupType!=null,"group_type", groupType);
		
		List<StatisticsDayEntity> lastYearData = statisticsDayService.list(lastWeekQuery);

		// 构建返回结果
		result.put("yesterdayData", yesterdayData);
		result.put("beforeYesterdayData", beforeYesterdayData);
		result.put("lastYearData", lastYearData);
		result.put("date", DateUtils.parseDateToStr("yyyy-MM", curMonth));
		result.put("type", "天统计");

		return result;
	}

	@Override
	public Map<String, Object> list12MonthlyStatistics(String yearStr,String deviceCode, String address, Long groupId,Integer groupType) {
		Map<String, Object> result = new HashMap<>();

		// 获取上个月的日期
		Date lastMonth = DateUtil.parse(yearStr, "yyyy");
		
		Date startOfLastMonth = DateUtils.getMonthFirstDayOfDate(lastMonth);
		Date endOfLastMonth = DateUtils.getMonthLastDayOfDate( DateUtils.addMonths(lastMonth, -12));

		// 查询上个月的月统计数据
		QueryWrapper<StatisticsMonthEntity> lastMonthQuery = new QueryWrapper<>();
		lastMonthQuery.between("month", startOfLastMonth, endOfLastMonth);
		lastMonthQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastMonthQuery.eq(address!=null,"address", address);
		lastMonthQuery.eq(groupId!=null,"group_id", groupId);
		lastMonthQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsMonthEntity> lastMonthData = statisticsMonthService.list(lastMonthQuery);

		// 获取上上个月的日期（用于环比）
		Date beforeLastMonth =DateUtils.addMonths(lastMonth, -2);
		Date startOfBeforeLastMonth = DateUtils.getMonthFirstDayOfDate(beforeLastMonth);
		Date endOfBeforeLastMonth = DateUtils.getMonthLastDayOfDate( DateUtils.addMonths(beforeLastMonth, -12));

		// 查询上上个月的月统计数据（用于环比）
		QueryWrapper<StatisticsMonthEntity> beforeLastMonthQuery = new QueryWrapper<>();
		beforeLastMonthQuery.between("month", startOfBeforeLastMonth, endOfBeforeLastMonth);
		beforeLastMonthQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeLastMonthQuery.eq(address!=null,"address", address);
		beforeLastMonthQuery.eq(groupId!=null,"group_id", groupId);
		beforeLastMonthQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsMonthEntity> beforeLastMonthData = statisticsMonthService.list(beforeLastMonthQuery);

		// 获取去年同期的日期（用于同比）
		Date lastYearSameMonth = DateUtils.addYears(lastMonth, -1);
		lastYearSameMonth = DateUtils.addMonths(lastYearSameMonth, -1); // 上个月
		Date startOfLastYearSameMonth = DateUtils.getMonthFirstDayOfDate(lastYearSameMonth);
		Date endOfLastYearSameMonth = DateUtils.getMonthLastDayOfDate(DateUtils.addMonths(lastYearSameMonth, -12));

		// 查询去年同期的月统计数据（用于同比）
		QueryWrapper<StatisticsMonthEntity> lastYearQuery = new QueryWrapper<>();
		lastYearQuery.between("month", startOfLastYearSameMonth, endOfLastYearSameMonth);
		lastYearQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastYearQuery.eq(address!=null,"address", address);
		lastYearQuery.eq(groupId!=null,"group_id", groupId);
		lastYearQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsMonthEntity> lastYearData = statisticsMonthService.list(lastYearQuery);

		// 构建返回结果
		result.put("lastMonthData", lastMonthData);
		result.put("beforeLastMonthData", beforeLastMonthData);
		result.put("lastYearData", lastYearData);
		result.put("date", DateUtils.parseDateToStr("yyyy-MM", lastMonth));
		result.put("type", "月统计");
		return result;
	}

	@Override
	public Map<String, Object> list3YearlyStatistics(String deviceCode, String address, Long groupId, Integer groupType) {
		Map<String, Object> result = new HashMap<>();

		// 获取去年的年份
		Date lastYear = DateUtils.addYears(new Date(), -1);
		Date startOfLastYear = DateUtils.getYearFirstDayOfDate(lastYear);
		Date endOfLastYear = DateUtils.getYearLastDayOfDate(lastYear);
		// 查询去年的年统计数据
		QueryWrapper<StatisticsYearEntity> lastYearQuery = new QueryWrapper<>();
		lastYearQuery.between("year", getYearValue(startOfLastYear), getYearValue(endOfLastYear));
		lastYearQuery.eq(deviceCode!=null,"device_code", deviceCode);
		lastYearQuery.eq(address!=null,"address", address);
		lastYearQuery.eq(groupId!=null,"group_id", groupId);
		lastYearQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsYearEntity>  lastYearData = statisticsYearService.list(lastYearQuery);

		// 获取前年的日期（用于环比）
		Date beforeLastYear = DateUtils.addYears(new Date(), -2);
		Date startOfBeforeLastYear = DateUtils.getYearFirstDayOfDate(beforeLastYear);
		Date endOfBeforeLastYear = DateUtils.getYearLastDayOfDate(beforeLastYear);

		// 查询前年的年统计数据（用于环比）
		QueryWrapper<StatisticsYearEntity> beforeLastYearQuery = new QueryWrapper<>();
		beforeLastYearQuery.between("year", getYearValue(startOfBeforeLastYear), getYearValue(endOfBeforeLastYear));
		beforeLastYearQuery.eq(deviceCode!=null,"device_code", deviceCode);
		beforeLastYearQuery.eq(address!=null,"address", address);
		beforeLastYearQuery.eq(groupId!=null,"group_id", groupId);
		beforeLastYearQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsYearEntity>  beforeLastYearData = statisticsYearService.list(beforeLastYearQuery);

		// 获取前年的前一年日期（用于同比）
		Date threeYearsAgo = DateUtils.addYears(new Date(), -3);
		Date startOfThreeYearsAgo = DateUtils.getYearFirstDayOfDate(threeYearsAgo);
		Date endOfThreeYearsAgo = DateUtils.getYearLastDayOfDate(threeYearsAgo);

		// 查询前年的前一年年统计数据（用于同比）
		QueryWrapper<StatisticsYearEntity> threeYearsAgoQuery = new QueryWrapper<>();
		threeYearsAgoQuery.between("year", getYearValue(startOfThreeYearsAgo), getYearValue(endOfThreeYearsAgo));
		threeYearsAgoQuery.eq(deviceCode!=null,"device_code", deviceCode);
		threeYearsAgoQuery.eq(address!=null,"address", address);
		threeYearsAgoQuery.eq(groupId!=null,"group_id", groupId);
		threeYearsAgoQuery.eq(groupType!=null,"group_type", groupType);
		List<StatisticsYearEntity>  threeYearsAgoData = statisticsYearService.list(threeYearsAgoQuery);
		// 构建返回结果
		result.put("lastYearData", lastYearData);
		result.put("beforeLastYearData", beforeLastYearData);
		result.put("threeYearsAgoData", threeYearsAgoData);
		result.put("date", String.valueOf(getYearValue(startOfLastYear)));
		result.put("type", "年统计");

		return result;
	}
	
	 	@Override
	    public Map<String, Object> getDayPieStatistics(Date startDate,Date endDate,Integer groupType,Integer energyType) {
	        Map<String, Object> result = new HashMap<>();
	        // 查询最近一个月的报警记录，按处理状态分组统计
	        QueryWrapper<StatisticsDayEntity> queryWrapper = new QueryWrapper<>();
	        if(startDate!=null&&endDate!=null)queryWrapper.between("day", startDate, endDate);
 		// 按设备ID、协议、地址和分组进行分组查询
			queryWrapper.select(
				"group_id", 
				"group_name as groupName", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.eq(groupType!=null,"group_type",groupType);
	        queryWrapper.isNotNull("group_id");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.groupBy("group_id", "group_name");
	        List<Map<String, Object>> stats = statisticsDayService.listMaps(queryWrapper);
	        result.put("stats", stats);
	        return result;
	    }
	    @Override
	    public Map<String, Object> getMonthPieStatistics(Date startDate,Date endDate,Integer groupType,Integer energyType) {
	        Map<String, Object> result = new HashMap<>();
	        // 查询最近一个月的报警记录，按处理状态分组统计
	        QueryWrapper<StatisticsMonthEntity> queryWrapper = new QueryWrapper<>();
	        if(startDate!=null&&endDate!=null)queryWrapper.between("month", startDate, endDate);
    		// 按设备ID、协议、地址和分组进行分组查询
 			queryWrapper.select(
 				"group_id", 
 				"group_name as groupName", 
 				"COUNT(id) as count", 
 				"SUM(carbon_emissions) as carbonEmissions", 
 				"SUM(cost_money) as cost_money", 
 				"SUM(sum_value) as sum_value", 
 				"AVG(average_value) as average_value", 
 				"MIN(min_value) as min_value", 
 				"MAX(max_value) as max_value", 
 				"SUM(count) as countNum"
 			);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.eq(groupType!=null,"group_type",groupType);
	        queryWrapper.isNotNull("group_id");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.groupBy("group_id", "group_name");
	        List<Map<String, Object>> stats = statisticsMonthService.listMaps(queryWrapper);
	        result.put("stats", stats);
	        return result;
	    }
	    @Override
	    public Map<String, Object> getYearPieStatistics(Integer year,Integer groupType,Integer energyType) {
	        Map<String, Object> result = new HashMap<>();
	        // 查询最近一个月的报警记录，按处理状态分组统计
	        QueryWrapper<StatisticsYearEntity> queryWrapper = new QueryWrapper<>();
	        if(year!=null)queryWrapper.eq("year", year);
    		// 按设备ID、协议、地址和分组进行分组查询
 			queryWrapper.select(
 				"group_id", 
 				"group_name as groupName", 
 				"COUNT(id) as count", 
 				"SUM(carbon_emissions) as carbonEmissions", 
 				"SUM(cost_money) as cost_money", 
 				"SUM(sum_value) as sum_value", 
 				"AVG(average_value) as average_value", 
 				"MIN(min_value) as min_value", 
 				"MAX(max_value) as max_value", 
 				"SUM(count) as countNum"
 			);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.eq(groupType!=null,"group_type",groupType);
	        queryWrapper.isNotNull("group_id");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.groupBy("group_id", "group_name");
	        List<Map<String, Object>> stats = statisticsYearService.listMaps(queryWrapper);
	        result.put("stats", stats);
	        return result;
	    }
	    
	    @Override
	    public Map<String, Object> getHourPieStatistics(String statTime,Integer groupType,Integer energyType) {
	        Map<String, Object> result = new HashMap<>();
	        Integer statTimeType=2;
	         Date curDate = new Date();
	         // 获取昨天的日期
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		    curDate = DateUtil.parse(statTime, "yyyy");
	 			statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	        QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	        queryWrapper.between("hour", startOfDay, endOfDay);
 		   // 按设备ID、协议、地址和分组进行分组查询
			queryWrapper.select(
				"group_id", 
				"group_name as groupName", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
//	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.eq(groupType!=null,"group_type",groupType);
	        queryWrapper.isNotNull("group_id");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.groupBy("group_id", "group_name"); 
	        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	        result.put("stats", stats);
	        
	        QueryWrapper<StatisticsHourlyEntity> queryTotalWrapper = new QueryWrapper<>();
	        queryTotalWrapper.between("hour", startOfDay, endOfDay);
 		   // 按设备ID、协议、地址和分组进行分组查询
	        queryTotalWrapper.select(
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryTotalWrapper.eq("cost_state",10);
	        queryTotalWrapper.eq("statistics_type",10);//所有设备值 不含虚拟设备
	        List<Map<String, Object>> totalStats = statisticsHourlyService.listMaps(queryTotalWrapper);
	        result.put("totalStats", totalStats);
	        
	        return result;
	    }
	    @Override
	    public Map<String, Object> getHourListStatistics(String statTime,Integer groupType,Integer energyType) {
	        Map<String, Object> result = new HashMap<>();
	        Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		     curDate = DateUtil.parse(statTime, "yyyy");
	 			 statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
	        
	        QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	        queryWrapper.between("hour", startOfDay, endOfDay);
			queryWrapper.select(
				 hourSql,
				"group_id", 
				"group_name as groupName", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.eq(groupType!=null,"group_type",groupType);
	        queryWrapper.isNotNull("group_id");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.eq("statistics_type",30);
	        queryWrapper.groupBy(hourGroupSql,"group_id", "group_name"); 
	        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	        result.put("stats", stats);
	        return result;
	    }
	    
	    
	    @Override
	    public Map<String, Object> getHourDeepStatCost(String statTime,Long groupId,Integer groupType,Integer energyType) {
	        Map<String, Object> result = new HashMap<>();
	        Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		     curDate = DateUtil.parse(statTime, "yyyy");
	 			 statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
	        
	        QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	        queryWrapper.between("hour", startOfDay, endOfDay);
			queryWrapper.select(
				 hourSql,
				"group_id", 
				"energy_type as energyType", 
				"group_name as groupName", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.eq(groupType!=null,"group_type",groupType);
	        queryWrapper.isNotNull("group_id");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.eq("statistics_type",30);
	        queryWrapper.groupBy(hourGroupSql,"group_id", "group_name","energy_type"); 
	        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	        for (Map<String, Object> stat : stats) {
	    		Integer energyTypeKey = (Integer) stat.get("energyType");
	    		stat.put("statisticsTypeName", ENERGY_TYPES_ENUM.findByCode(energyTypeKey).getName());
	    	}
	        result.put("stats", stats);
	        QueryWrapper<StatisticsHourlyEntity> queryTotalWrapper = new QueryWrapper<>();
	        queryTotalWrapper.between("hour", startOfDay, endOfDay);
	        queryTotalWrapper.select(
				"group_id", 
				"energy_type as energyType", 
				"group_name as groupName", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryTotalWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryTotalWrapper.eq(groupType!=null,"group_type",groupType);
	        queryTotalWrapper.isNotNull("group_id");
	        queryTotalWrapper.eq("cost_state",10);
	        queryTotalWrapper.eq("statistics_type",30);
	        queryTotalWrapper.groupBy("group_id", "group_name","energy_type"); 
	        List<Map<String, Object>> totalStat = statisticsHourlyService.listMaps(queryTotalWrapper);
	        result.put("totalStat", totalStat);
	        for (Map<String, Object> stat : totalStat) {
	    		Integer energyTypeKey = (Integer) stat.get("energyType");
	    		stat.put("statisticsTypeName", ENERGY_TYPES_ENUM.findByCode(energyTypeKey).getName());
	    	}
	        return result;
	    }
	    
	    @Override
	    public Map<String, Object> getHourElectricityCostTypePieStatistics(String statTime) {
	        Map<String, Object> result = new HashMap<>();
	        Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		     curDate = DateUtil.parse(statTime, "yyyy");
	 			 statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
			QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	    	if(startOfDay!=null&&endOfDay!=null)queryWrapper.between("hour", startOfDay, endOfDay);
 		   // 按设备ID、协议、地址和分组进行分组查询
			queryWrapper.select(
				"cost_type as costType", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as costMoney", 
				"SUM(sum_value) as sumValue", 
				"AVG(average_value) as totalAvg", 
				"MIN(min_value) as totalMin", 
				"MAX(max_value) as totalMax", 
				"SUM(count) as totalCount"
			);
	        queryWrapper.eq("energy_type",ENERGY_TYPES_ENUM.Electricity.getCode());
	        queryWrapper.isNotNull("device_code");
	        queryWrapper.isNotNull("cost_type");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.eq("statistics_type",10);
	        queryWrapper.groupBy("cost_type"); 
	        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	        
	        result.put("stats", stats);
	        return result;
	    }
	    @Override
	    public Map<String, Object> getHourElectricityCostTypeListStatistics(String statTime) {
	        Map<String, Object> result = new HashMap<>();
	        Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		     curDate = DateUtil.parse(statTime, "yyyy");
	 			 statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
			// 查询最近一个月的报警记录，按处理状态分组统计
	    	QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	    	if(startOfDay!=null&&endOfDay!=null)queryWrapper.between("hour", startOfDay, endOfDay);
			queryWrapper.select(
					hourSql,
				"cost_type as costType", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.eq("energy_type",ENERGY_TYPES_ENUM.Electricity.getCode());
	        queryWrapper.isNull("group_id");//仅仅统计设备类型 
	        queryWrapper.isNotNull("device_code");
	        queryWrapper.isNotNull("cost_type");
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.groupBy(hourGroupSql,"cost_type"); 
	        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	        result.put("stats", stats);
	        return result;
	    }
	    @Override
	    public Map<String, Object> getHourEnergyTypePieStatistics(String statTime) {
	        Map<String, Object> result = new HashMap<>();
	        Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		     curDate = DateUtil.parse(statTime, "yyyy");
	 			 statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
	    	// 查询最近一个月的报警记录，按处理状态分组统计
	    	QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	    	if(startOfDay!=null&&endOfDay!=null)queryWrapper.between("hour", startOfDay, endOfDay);
	        
 		   // 按设备ID、协议、地址和分组进行分组查询
			queryWrapper.select(
				"energy_type as energyType", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.isNull("group_id");//仅仅统计设备类型 
	        queryWrapper.isNotNull("device_code");
	        queryWrapper.ge("energy_type", 0);
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.groupBy("energy_type"); 
	        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	        int total = 0;
	        for (Map<String, Object> stat : stats) {
	        	Integer energyType = (Integer) stat.get("energyType");
	            Long count = (Long) stat.get("count");
	            if (count != null) {
	            	total += count.intValue();
	            }
	            stat.put("statisticsTypeName", ENERGY_TYPES_ENUM.findByCode(energyType).getName());
	        }
	        result.put("total", total);
	        result.put("stats", stats);
	        return result;
	    }
	    @Override
	    public Map<String, Object> getHourEnergyTypeGroupListStatistics(String statTime) {
	    	Map<String, Object> result = new HashMap<>();
	    	 Integer statTimeType=2;
	         Date curDate = new Date();
	         // 获取昨天的日期
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		     curDate = DateUtil.parse(statTime, "yyyy");
	 			 statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
	    	
	    	// 查询最近一个月的报警记录，按处理状态分组统计
	    	QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	    	if(startOfDay!=null&&endOfDay!=null)queryWrapper.between("hour", startOfDay, endOfDay);
	    	// 按设备ID、协议、地址和分组进行分组查询
	    	queryWrapper.select(
	    			 hourSql,
	    			"energy_type as energyType", 
	    			"COUNT(id) as count", 
	    			"SUM(carbon_emissions) as carbonEmissions", 
	    			"SUM(cost_money) as cost_money", 
	    			"SUM(sum_value) as sum_value", 
	    			"AVG(average_value) as average_value", 
	    			"MIN(min_value) as min_value", 
	    			"MAX(max_value) as max_value", 
	    			"SUM(count) as countNum"
	    			);
	    	queryWrapper.isNull("group_id");//仅仅统计设备类型 
	    	queryWrapper.isNotNull("device_code");
	    	queryWrapper.ge("energy_type", 0);
	    	queryWrapper.eq("cost_state",10);
	    	queryWrapper.groupBy(hourGroupSql,"energy_type"); 
	    	List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
	    	int total = 0;
	    	for (Map<String, Object> stat : stats) {
	    		Integer energyType = (Integer) stat.get("energyType");
	    		Long count = (Long) stat.get("count");
	    		if (count != null) {
	    			total += count.intValue();
	    		}
	    		stat.put("statisticsTypeName", ENERGY_TYPES_ENUM.findByCode(energyType).getName());
	    	}
	    	result.put("total", total);
	    	result.put("stats", stats);
	    	return result;
	    }
	    /**
		 * 获取小时统计数据（昨天的合计数据），包括同比和环比
		 */
		@Override
		public Map<String, Object> getHourlyStatisticsCost(String statTime,Integer energyType) {
			Map<String, Object> result = new HashMap<>();
			 Integer statTimeType=2;
	         Date curDate = new Date();
	         // 获取昨天的日期
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
			// 获取前天的日期（用于环比）
			Date beforeDay = DateUtils.addDays(curDate, -1);
			Date startOfBeforeDay = DateUtils.getStartOfDate(beforeDay);
			Date endOfBeforeDay = DateUtils.getEndOfDate(beforeDay);
			// 获取去年同一天的日期（用于同比）
			Date lastYearDay = DateUtils.addYears(curDate, -1);
			Date startOfLastYearDay = DateUtils.getStartOfDate(lastYearDay);
			Date endOfLastYearDay = DateUtils.getEndOfDate(lastYearDay);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
				 // 获取前天的日期（用于环比）
				 beforeDay = DateUtils.addMonths(curDate, -1);
				 startOfBeforeDay = DateUtil.getStartOfMonth(beforeDay);
				 endOfBeforeDay = DateUtil.getEndOfMonth(beforeDay);
				 // 获取去年同一天的日期（用于同比）
				 lastYearDay = DateUtils.addYears(curDate, -1);
				 startOfLastYearDay = DateUtil.getStartOfMonth(lastYearDay);
				 endOfLastYearDay = DateUtil.getEndOfMonth(lastYearDay);
	 		} else if (statTime.length() == 4) {
	 		    curDate = DateUtil.parse(statTime, "yyyy");
	 			statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
				 // 获取前天的日期（用于环比）
				 beforeDay = DateUtils.addYears(curDate, -1);
				 startOfBeforeDay = DateUtil.getStartOfYear(beforeDay);
				 endOfBeforeDay = DateUtil.getEndOfYear(beforeDay);
				 // 获取去年同一天的日期（用于同比）
				 lastYearDay = DateUtils.addYears(curDate, -2);
				 startOfLastYearDay = DateUtil.getStartOfYear(lastYearDay);
				 endOfLastYearDay = DateUtil.getEndOfYear(lastYearDay);
	 		}
			// 查询昨天的小时统计数据
			QueryWrapper<StatisticsHourlyEntity> dayQuery = new QueryWrapper<>();
			dayQuery.select(
					"COUNT(id) as count", 
					"SUM(carbon_emissions) as carbonEmissions", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			dayQuery.between("hour", startOfDay, endOfDay);
			dayQuery.eq("cost_state",10);
			dayQuery.eq(energyType!=null,"energy_type",energyType);
			Map<String, Object> dayData = statisticsHourlyService.getMap(dayQuery);
			// 查询前天的小时统计数据（用于环比）
			QueryWrapper<StatisticsHourlyEntity> beforeYesterdayQuery = new QueryWrapper<>();
			beforeYesterdayQuery.select(
					"COUNT(id) as count", 
					"SUM(carbon_emissions) as carbonEmissions", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			beforeYesterdayQuery.between("hour", startOfBeforeDay, endOfBeforeDay);
			beforeYesterdayQuery.eq("cost_state",10);
			beforeYesterdayQuery.eq(energyType!=null,"energy_type",energyType);
			Map<String, Object> beforedayData = statisticsHourlyService.getMap(beforeYesterdayQuery);
			// 查询上周同一天的小时统计数据（用于同比）
			QueryWrapper<StatisticsHourlyEntity> lastYearDayQuery = new QueryWrapper<>();
			lastYearDayQuery.select(
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
			lastYearDayQuery.between("hour", startOfLastYearDay, endOfLastYearDay);
			lastYearDayQuery.eq("cost_state",10);
			lastYearDayQuery.eq(energyType!=null,"energy_type",energyType);
			Map<String, Object> lastYearDayData = statisticsHourlyService.getMap(lastYearDayQuery);
			result.put("dayData", dayData);
			result.put("beforedayData", beforedayData);
			result.put("lastYearDayData", lastYearDayData);
			result.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", curDate));
			result.put("type", "小时统计");
			return result;
		}
		
		
		 /**
		 * 获取小时统计数据（昨天的合计数据），包括同比和环比
		 */
		@Override
		public Map<String, Object> getHourlyStatisticsByGroupId(String statTime, Long groupId,Integer energyType) {
			List<DeviceGroupVO> deviceList= deviceGroupService.getByGroupId(groupId, 1);//分组有效设备查询
			List<String> deviceCodeList = deviceList.stream().map(DeviceGroupVO::getGroupDeviceCode).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
			Map<String, Object> result = new HashMap<>();
			 Integer statTimeType=2;
	         Date curDate = new Date();
	         // 获取昨天的日期
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
			// 获取前天的日期（用于环比）
			Date beforeDay = DateUtils.addDays(curDate, -1);
			Date startOfBeforeDay = DateUtils.getStartOfDate(beforeDay);
			Date endOfBeforeDay = DateUtils.getEndOfDate(beforeDay);
			// 获取去年同一天的日期（用于同比）
			Date lastYearDay = DateUtils.addYears(curDate, -1);
			Date startOfLastYearDay = DateUtils.getStartOfDate(lastYearDay);
			Date endOfLastYearDay = DateUtils.getEndOfDate(lastYearDay);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
				 // 获取前天的日期（用于环比）
				 beforeDay = DateUtils.addMonths(curDate, -1);
				 startOfBeforeDay = DateUtil.getStartOfMonth(beforeDay);
				 endOfBeforeDay = DateUtil.getEndOfMonth(beforeDay);
				 // 获取去年同一天的日期（用于同比）
				 lastYearDay = DateUtils.addYears(curDate, -1);
				 startOfLastYearDay = DateUtil.getStartOfMonth(lastYearDay);
				 endOfLastYearDay = DateUtil.getEndOfMonth(lastYearDay);
	 		} else if (statTime.length() == 4) {
	 		    curDate = DateUtil.parse(statTime, "yyyy");
	 			statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
				 // 获取前天的日期（用于环比）
				 beforeDay = DateUtils.addYears(curDate, -1);
				 startOfBeforeDay = DateUtil.getStartOfYear(beforeDay);
				 endOfBeforeDay = DateUtil.getEndOfYear(beforeDay);
				 // 获取去年同一天的日期（用于同比）
				 lastYearDay = DateUtils.addYears(curDate, -2);
				 startOfLastYearDay = DateUtil.getStartOfYear(lastYearDay);
				 endOfLastYearDay = DateUtil.getEndOfYear(lastYearDay);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
			// 查询昨天的小时统计数据
			QueryWrapper<StatisticsHourlyEntity> dayQuery = new QueryWrapper<>();
			dayQuery.select(
					hourSql,
					"SUM(carbon_emissions) as carbonEmissions", 
					"COUNT(id) as count", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			dayQuery.between("hour", startOfDay, endOfDay);
			dayQuery.eq("cost_state",10);
			dayQuery.in(deviceCodeList!=null&&deviceCodeList.size()>0,"device_code", deviceCodeList);
			dayQuery.eq(energyType!=null,"energy_type",energyType);
			dayQuery.groupBy(hourGroupSql); 
			List<Map<String, Object>>  dayData = statisticsHourlyService.listMaps(dayQuery);
			// 查询前天的小时统计数据（用于环比）
			QueryWrapper<StatisticsHourlyEntity> beforeYesterdayQuery = new QueryWrapper<>();
			beforeYesterdayQuery.select(
					hourSql,
					"SUM(carbon_emissions) as carbonEmissions", 
					"COUNT(id) as count", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			beforeYesterdayQuery.between("hour", startOfBeforeDay, endOfBeforeDay);
			beforeYesterdayQuery.eq("cost_state",10);
			beforeYesterdayQuery.in(deviceCodeList!=null&&deviceCodeList.size()>0,"device_code", deviceCodeList);
			beforeYesterdayQuery.eq(energyType!=null,"energy_type",energyType);
			beforeYesterdayQuery.groupBy(hourGroupSql); 
			List<Map<String, Object>>  beforedayData = statisticsHourlyService.listMaps(beforeYesterdayQuery);
			// 查询上周同一天的小时统计数据（用于同比）
			QueryWrapper<StatisticsHourlyEntity> lastYearDayQuery = new QueryWrapper<>();
			lastYearDayQuery.select(
				 hourSql,
				 "SUM(carbon_emissions) as carbonEmissions", 
				"COUNT(id) as count", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
			lastYearDayQuery.between("hour", startOfLastYearDay, endOfLastYearDay);
			lastYearDayQuery.eq("cost_state",10);
			lastYearDayQuery.in(deviceCodeList!=null&&deviceCodeList.size()>0,"device_code", deviceCodeList);
			lastYearDayQuery.eq(energyType!=null,"energy_type",energyType);
			lastYearDayQuery.groupBy(hourGroupSql); 
			List<Map<String, Object>> lastYearDayData = statisticsHourlyService.listMaps(lastYearDayQuery);
			result.put("dayData", dayData);
			result.put("beforedayData", beforedayData);
			result.put("lastYearDayData", lastYearDayData);
			result.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", curDate));
			result.put("type", "小时统计");
			return result;
		}
		 /**
			 * 获取小时统计数据（昨天的合计数据） 分单元 分组统计
			 */
			@Override
			public Map<String, Object> getHourlyStatisticsByGroupAndDeviceCode(String statTime, Long groupId,Integer energyType,Integer groupType) {
				List<DeviceGroupVO> deviceList= deviceGroupService.getByGroupId(groupId,1);//分组有效设备查询
				List<String> deviceCodeList = deviceList.stream().map(DeviceGroupVO::getGroupDeviceCode).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
				Map<String, DeviceGroupVO> deviceMap =deviceList.stream().collect(Collectors.toMap(DeviceGroupVO::getGroupDeviceCode, item -> item));
				
				Map<String, Object> result = new HashMap<>();
				 Integer statTimeType=2;
		         Date curDate = new Date();
				Date startOfDay = DateUtils.getStartOfDate(curDate);
				Date endOfDay = DateUtils.getEndOfDate(curDate);
		 		if (statTime == null) {
		 		} else if (statTime.length() == 10) {
		 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
		 		     startOfDay = DateUtils.getStartOfDate(curDate);
		 		     endOfDay = DateUtils.getEndOfDate(curDate);
		 			 statTimeType=2;
		 		} else if (statTime.length() == 7) {
		 			 statTimeType=3;
		 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
					 startOfDay = DateUtil.getStartOfMonth(curDate);
					 endOfDay = DateUtil.getEndOfMonth(curDate);
		 		} else if (statTime.length() == 4) {
		 		    curDate = DateUtil.parse(statTime, "yyyy");
		 			statTimeType=4;
					 startOfDay = DateUtil.getStartOfYear(curDate);
					 endOfDay = DateUtil.getEndOfYear(curDate);
		 		}
		 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
				String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
				if(statTimeType==2) {//天
				}else if(statTimeType==3) {//月
					 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
					 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
				}else if(statTimeType==4) {//月
					 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
					 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
				}
				// 查询昨天的小时统计数据
				QueryWrapper<StatisticsHourlyEntity> dayQuery = new QueryWrapper<>();
				dayQuery.select(
						hourSql,
						"SUM(carbon_emissions) as carbonEmissions", 
						"device_code as deviceCode",
						"COUNT(id) as count", 
						"SUM(cost_money) as cost_money", 
						"SUM(sum_value) as sum_value", 
						"AVG(average_value) as average_value", 
						"MIN(min_value) as min_value", 
						"MAX(max_value) as max_value", 
						"SUM(count) as countNum"
					);
				dayQuery.between("hour", startOfDay, endOfDay);
				dayQuery.eq("cost_state",10);
				dayQuery.in(deviceCodeList!=null&&deviceCodeList.size()>0,"device_code", deviceCodeList);
				dayQuery.eq(energyType!=null,"energy_type",energyType);
				dayQuery.eq(groupType!=null,"group_type",groupType);
				dayQuery.groupBy(hourGroupSql,"device_code"); 
				List<Map<String, Object>>  dayData = statisticsHourlyService.listMaps(dayQuery);
		        for (Map<String, Object> stat : dayData) {
		        	String deviceCode = (String) stat.get("deviceCode");
		        	DeviceGroupVO deviceGroupVO=deviceMap.get(deviceCode);
		        	if(deviceGroupVO!=null) {
		        		stat.put("deviceName", deviceGroupVO.getGroupDeviceName());
		        	}
		        }
				result.put("dayData", dayData);
				result.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", curDate));
				result.put("type", "小时统计");
				return result;
			}
		 @Override
		 public Map<String, Object> flowAnalysis(String statTime,Integer energyType) {
			 Map<String, Object> result = new HashMap<>();
			 Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 		     startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 			 statTimeType=2;
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		    curDate = DateUtil.parse(statTime, "yyyy");
	 			statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		List<FlowDataVo> flowDataVos=new ArrayList<>();
	 		QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
	        queryWrapper.between("hour", startOfDay, endOfDay);
			queryWrapper.select(
				"group_id as groupId", 
				"group_name as groupName", 
				"COUNT(id) as count", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(sum_value) as sum_value", 
				"AVG(average_value) as average_value", 
				"MIN(min_value) as min_value", 
				"MAX(max_value) as max_value", 
				"SUM(count) as countNum"
			);
	        queryWrapper.eq("cost_state",10);
	        queryWrapper.eq("statistics_type",30);
	        queryWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryWrapper.groupBy("group_id", "group_name"); 
	        List<Map<String, Object>> groupStats = statisticsHourlyService.listMaps(queryWrapper);
	        Map<Long, Double> groupCarbonMap =new HashMap<Long, Double>();
	        for (Map<String, Object> stat : groupStats) {
	        	Long groupId = (Long) stat.get("groupId");
	        	Double carbonEmissions = (Double) stat.get("cost_money");
	        	groupCarbonMap.put(groupId, carbonEmissions);
	        }
	        log.info("=====groupCarbonMap======="+JsonUtil.getJsonByObj(groupCarbonMap));
	        QueryWrapper<GroupEntity> queryGroupWrapper=new QueryWrapper<>();
	    	queryGroupWrapper.orderByDesc("group_id");
	        List<GroupEntity> groupList = groupService.list(queryGroupWrapper);
	        Map<Long, GroupEntity> groupMap =groupList.stream().collect(Collectors.toMap(GroupEntity::getGroupId, item -> item));
	        
	        
	        QueryWrapper<StatisticsHourlyEntity> queryDeviceWrapper = new QueryWrapper<>();
	        queryDeviceWrapper.between("hour", startOfDay, endOfDay);
	        queryDeviceWrapper.select(
				"device_code as deviceCode", 
				"SUM(carbon_emissions) as carbonEmissions", 
				"SUM(cost_money) as cost_money", 
				"SUM(count) as countNum"
			);
	        queryDeviceWrapper.eq("cost_state",10);
	        queryDeviceWrapper.eq("statistics_type",10);
	        queryDeviceWrapper.eq(energyType!=null,"energy_type",energyType);
	        queryDeviceWrapper.groupBy("device_code"); 
	        List<Map<String, Object>> deviceStats = statisticsHourlyService.listMaps(queryDeviceWrapper);
	        Map<String, Double> deviceStatsMap =new HashMap<String, Double>();
	        for (Map<String, Object> stat : deviceStats) {
	        	String deviceCode = (String) stat.get("deviceCode");
	        	Double carbonEmissions = (Double) stat.get("cost_money");
	        	deviceStatsMap.put(deviceCode, carbonEmissions);
	        }
	        log.info("=====deviceStatsMap======="+JsonUtil.getJsonByObj(deviceStatsMap));
	        Map<Long, Boolean> groupHasSonMap =new HashMap<Long, Boolean>();
	        List<Long> firstGroupIds=new ArrayList<Long>();
	        List<Long> subGroupIds=new ArrayList<Long>();
	        firstGroupIds=groupList.stream().filter(map->map.getGroupType()==0).map(GroupEntity::getGroupId).collect(Collectors.toList());
	        subGroupIds=groupList.stream().filter(map->map.getGroupType()==10).map(GroupEntity::getGroupId).collect(Collectors.toList());
	        log.info("=====firstGroupIds======="+JsonUtil.getJsonByObj(firstGroupIds));
	        log.info("=====subGroupIds======="+JsonUtil.getJsonByObj(subGroupIds));
	        for(GroupEntity item:groupList) {
	        	if(item.getParentGroupId()!=null&&item.getParentGroupId()>0) {
	        		GroupEntity parentGroup=groupMap.get(item.getParentGroupId());
	        		if(parentGroup!=null) {
	        			 FlowDataVo flowDataVo=new FlowDataVo(parentGroup.getGroupName(), item.getGroupName(), groupCarbonMap.get(item.getGroupId()));
	 	        	     flowDataVos.add(flowDataVo);
	        		}
	        		groupHasSonMap.put(item.getParentGroupId(), true);
	        	}else {
	        		FlowDataVo flowDataVo=new FlowDataVo("", item.getGroupName(), groupCarbonMap.get(item.getGroupId()));
	        		flowDataVos.add(flowDataVo);
	        		groupHasSonMap.put(item.getGroupId(), true);
	        		firstGroupIds.add(item.getGroupId());
	        	}
	        }
	        log.info("=====groupHasSonMap======="+JsonUtil.getJsonByObj(groupHasSonMap));
	        for(GroupEntity item:groupList) {
	        	if(groupHasSonMap.containsKey(item.getGroupId())) {
	        	}else {
	        		List<DeviceGroupVO> deviceList= deviceGroupService.getByGroupId(item.getGroupId(), 1);//分组有效设备查询
		        	if(deviceList!=null&&deviceList.size()>0) {
		        		for(DeviceGroupVO deviceGroupVO:deviceList) {
		        			    if(deviceGroupVO.getEnergyType()==energyType) {
		        			    	FlowDataVo flowDataVo=new FlowDataVo(item.getGroupName(),deviceGroupVO.getGroupDeviceName(), deviceStatsMap.get(deviceGroupVO.getGroupDeviceCode()));
				        			flowDataVos.add(flowDataVo);
		        			    }
			        	}
		        	}
	        	}
	        }
	 		result.put("flowDataVos", flowDataVos);
	 		
	 		if(firstGroupIds==null||firstGroupIds.size()<=0) {
	 			return result;
	 		}
	 		List<DeviceGroupEntity> totalDeviceList= deviceGroupService.listByGroupId(firstGroupIds, energyType,1);//分组有效设备查询
	 		List<Long> deviceIdList = totalDeviceList.stream().map(DeviceGroupEntity::getDeviceId).collect(Collectors.toList());
	 		if(deviceIdList!=null&&deviceIdList.size()>0) {
	 			QueryWrapper<StatisticsHourlyEntity> totalQuery = new QueryWrapper<>();
	 			totalQuery.select(
						"energy_type as energyType", 
						"SUM(carbon_emissions) as carbonEmissions", 
						"COUNT(id) as count", 
						"SUM(cost_money) as cost_money", 
						"SUM(sum_value) as sum_value", 
						"AVG(average_value) as average_value", 
						"MIN(min_value) as min_value", 
						"MAX(max_value) as max_value", 
						"SUM(count) as countNum"
					);
				totalQuery.between("hour", startOfDay, endOfDay);
				totalQuery.eq("cost_state",10);
				totalQuery.in("device_id",deviceIdList);
				totalQuery.eq(energyType!=null,"energy_type",energyType);
				totalQuery.gt("energy_type", 0);
				totalQuery.isNotNull("device_code");
				Map<String, Object>  totalData = statisticsHourlyService.getMap(totalQuery);
				result.put("totalData", totalData);
	 		}
			List<DeviceGroupEntity> totalSubDeviceList= deviceGroupService.listByGroupId(subGroupIds,energyType,1);//分组有效设备查询
	 		List<Long> subDeviceIdList = totalSubDeviceList.stream().map(DeviceGroupEntity::getDeviceId).collect(Collectors.toList());
	 		if(subDeviceIdList!=null&&subDeviceIdList.size()>0) {
	 			QueryWrapper<StatisticsHourlyEntity> totalSubQuery = new QueryWrapper<>();
		 		totalSubQuery.select(
						"energy_type as energyType", 
						"SUM(carbon_emissions) as carbonEmissions", 
						"COUNT(id) as count", 
						"SUM(cost_money) as cost_money", 
						"SUM(sum_value) as sum_value", 
						"AVG(average_value) as average_value", 
						"MIN(min_value) as min_value", 
						"MAX(max_value) as max_value", 
						"SUM(count) as countNum"
					);
		 		totalSubQuery.between("hour", startOfDay, endOfDay);
		 		totalSubQuery.eq("cost_state",10);
		 		totalSubQuery.in("device_id",subDeviceIdList);
		 		totalSubQuery.eq(energyType!=null,"energy_type",energyType);
		 		totalSubQuery.gt("energy_type", 0);
		 		totalSubQuery.isNotNull("device_code");
		 		Map<String, Object>  totalSubData = statisticsHourlyService.getMap(totalSubQuery);
				result.put("totalSubData", totalSubData);
	 		}
			return result;
		 }
		 @Override
		 public Map<String, Object> getHourlyStatisticsCarbon(String statTime, Long groupId) {
			 Map<String, Object> result = new HashMap<>();
			 Integer statTimeType=2;
	         Date curDate = new Date();
	         // 获取昨天的日期
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
			// 获取前天的日期（用于环比）
			Date beforeDay = DateUtils.addDays(curDate, -1);
			Date startOfBeforeDay = DateUtils.getStartOfDate(beforeDay);
			Date endOfBeforeDay = DateUtils.getEndOfDate(beforeDay);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 			 statTimeType=2;
	 			 startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 		     beforeDay = DateUtils.addDays(curDate, -1);
				 startOfBeforeDay = DateUtils.getStartOfDate(beforeDay);
				 endOfBeforeDay = DateUtils.getEndOfDate(beforeDay);
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
				 // 获取前天的日期（用于环比）
				 beforeDay = DateUtils.addMonths(curDate, -1);
				 startOfBeforeDay = DateUtil.getStartOfMonth(beforeDay);
				 endOfBeforeDay = DateUtil.getEndOfMonth(beforeDay);
	 		} else if (statTime.length() == 4) {
	 		    curDate = DateUtil.parse(statTime, "yyyy");
	 			statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
				 // 获取前天的日期（用于环比）
				 beforeDay = DateUtils.addYears(curDate, -1);
				 startOfBeforeDay = DateUtil.getStartOfYear(beforeDay);
				 endOfBeforeDay = DateUtil.getEndOfYear(beforeDay);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
			// 查询昨天的小时统计数据
			QueryWrapper<StatisticsHourlyEntity> dayQuery = new QueryWrapper<>();
			dayQuery.select(
					hourSql,
					"SUM(carbon_emissions) as carbonEmissions", 
					"COUNT(id) as count", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			dayQuery.between("hour", startOfDay, endOfDay);
			dayQuery.eq("cost_state",10);
			dayQuery.eq("statistics_type",10);
			dayQuery.isNotNull("device_code");
			dayQuery.groupBy(hourGroupSql); 
			List<Map<String, Object>>  dayData = statisticsHourlyService.listMaps(dayQuery);
			QueryWrapper<StatisticsHourlyEntity> beforeYesterdayQuery = new QueryWrapper<>();
			beforeYesterdayQuery.select(
					hourSql,
					"SUM(carbon_emissions) as carbonEmissions", 
					"COUNT(id) as count", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			beforeYesterdayQuery.between("hour", startOfBeforeDay, endOfBeforeDay);
			beforeYesterdayQuery.eq("cost_state",10);
			beforeYesterdayQuery.eq("statistics_type",10);
			beforeYesterdayQuery.isNotNull("device_code");
			beforeYesterdayQuery.groupBy(hourGroupSql); 
			List<Map<String, Object>>  beforedayData = statisticsHourlyService.listMaps(beforeYesterdayQuery);
			result.put("dayData", dayData);
			result.put("beforedayData", beforedayData);
			
			QueryWrapper<StatisticsHourlyEntity> totalQuery = new QueryWrapper<>();
			totalQuery.select(
					hourSql,
					"energy_type as energyType", 
					"SUM(carbon_emissions) as carbonEmissions", 
					"COUNT(id) as count", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
			totalQuery.between("hour", startOfDay, endOfDay);
			totalQuery.eq("cost_state",10);
			totalQuery.gt("energy_type",0);
			totalQuery.eq("statistics_type",10);
			totalQuery.isNotNull("device_code");
			totalQuery.groupBy("energy_type"); 
			List<Map<String, Object>>  totalData = statisticsHourlyService.listMaps(totalQuery);
			for (Map<String, Object> stat : totalData) {
	        	Integer energyTypeKey = (Integer) stat.get("energyType");
	        	ENERGY_TYPES_ENUM energyTypeEnum=ENERGY_TYPES_ENUM.findByCode(energyTypeKey);
	            stat.put("statisticsTypeName", energyTypeEnum.getName());
	            stat.put("statisticsTypeDw", energyTypeEnum.getDw());
	        }
			result.put("totalData", totalData);
			return result;
		 }
		 @Override
		 public Map<String, Object> listHourlyStatistics(String statTime, String deviceCode, String address,
				Long groupId, Integer groupType) {
			 Map<String, Object> result = new HashMap<>();
			 Integer statTimeType=2;
	         Date curDate = new Date();
			Date startOfDay = DateUtils.getStartOfDate(curDate);
			Date endOfDay = DateUtils.getEndOfDate(curDate);
	 		if (statTime == null) {
	 		} else if (statTime.length() == 10) {
	 		     curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
	 		     startOfDay = DateUtils.getStartOfDate(curDate);
	 		     endOfDay = DateUtils.getEndOfDate(curDate);
	 			 statTimeType=2;
	 		} else if (statTime.length() == 7) {
	 			 statTimeType=3;
	 			 curDate = DateUtil.parse(statTime, "yyyy-MM");
				 startOfDay = DateUtil.getStartOfMonth(curDate);
				 endOfDay = DateUtil.getEndOfMonth(curDate);
	 		} else if (statTime.length() == 4) {
	 		    curDate = DateUtil.parse(statTime, "yyyy");
	 			statTimeType=4;
				 startOfDay = DateUtil.getStartOfYear(curDate);
				 endOfDay = DateUtil.getEndOfYear(curDate);
	 		}
	 		String hourSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00') as hourName";
			String hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d %H:00')";
			if(statTimeType==2) {//天
			}else if(statTimeType==3) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m-%d') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m-%d')";
			}else if(statTimeType==4) {//月
				 hourSql="DATE_FORMAT(hour, '%Y-%m') as hourName";
				 hourGroupSql="DATE_FORMAT(hour, '%Y-%m')";
			}
		        QueryWrapper<StatisticsHourlyEntity> queryWrapper = new QueryWrapper<>();
		        queryWrapper.between("hour", startOfDay, endOfDay);
	 		   // 按设备ID、协议、地址和分组进行分组查询
				queryWrapper.select(
					hourSql,
					"group_id", 
					"group_name as groupName", 
					"COUNT(id) as count", 
					"SUM(carbon_emissions) as carbonEmissions", 
					"SUM(cost_money) as cost_money", 
					"SUM(sum_value) as sum_value", 
					"AVG(average_value) as average_value", 
					"MIN(min_value) as min_value", 
					"MAX(max_value) as max_value", 
					"SUM(count) as countNum"
				);
		        queryWrapper.eq("cost_state",10);
		        queryWrapper.eq(deviceCode!=null,"device_code", deviceCode);
		        queryWrapper.eq(address!=null,"address", address);
		        queryWrapper.eq(groupId!=null,"group_id", groupId);
		        queryWrapper.eq(groupType!=null,"group_type",groupType);
		        queryWrapper.groupBy(hourGroupSql); 
		        List<Map<String, Object>> stats = statisticsHourlyService.listMaps(queryWrapper);
		        result.put("stats", stats);
		        return result;
		 }

}
